package com.ai.dylan.spring.mcp.controller;

import com.ai.dylan.spring.mcp.entity.BookInfo;
import com.ai.dylan.spring.mcp.model.ChatRequest;
import com.ai.dylan.spring.mcp.model.ChatResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;
import java.util.List;

/**
 * 聊天控制器，处理AI聊天请求
 */
@RestController
@RequestMapping("/api/chat")
@Slf4j
public class ChatController {


    @Resource
    private ChatClient chatClient;


    /**
     * 处理聊天请求，使用AI和MCP工具进行响应
     *
     * @param request 聊天请求
     * @return 包含AI回复的响应
     */
    @PostMapping
    public ChatResponse<List<BookInfo>> chat(@RequestBody ChatRequest request) {
        try {
            // 创建用户消息
            String userMessage = request.getMessage();

            // 使用流式API调用聊天
            List<BookInfo> bookInfoList = chatClient.prompt()
                    .user(userMessage)
                    .call().entity(new ParameterizedTypeReference<>() {
                        @NotNull
                        @Override
                        public Type getType() {
                            return super.getType();
                        }
                    });
            ;
            return ChatResponse.ok(bookInfoList);
        } catch (Exception e) {
            log.error("处理请求时出错: {}", e.getMessage(), e);
            return ChatResponse.error("处理请求时出错: " + e.getMessage(), "500");
        }
    }
}
